package net.sakz.oss;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * sso对应的令牌认证器
 * @author hunter
 *
 */
public class TokerAuthenticator {
	protected static Logger logger = LoggerFactory.getLogger(LoginOutFilter.class);
	
	/**
	 * token认证
	 * @param token
	 * @param service
	 * @return
	 */
	public AuthenticatorRlt validate(String token, String service) {
		AuthenticatorRlt rlt=post(service+"?token="+token, AuthenticatorRlt.class);
		return rlt;
	}
	
	private <T> T post(String url, Class<T> cls) {
		T t = null;
		// 创建默认的httpClient实例.
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 创建httppost
		HttpPost httppost = new HttpPost(url);
		CloseableHttpResponse response = null;
		// 创建参数队列
		try {
			logger.info("executing request " + httppost.getURI());
			response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			ObjectMapper mapper = new ObjectMapper();
			String rlt=EntityUtils.toString(entity, "UTF-8");
			logger.info("repsone " + rlt);
			t = mapper.readValue(rlt, cls);
			return t;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				if (response != null) {
					response.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				httpclient.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return t;
	}
}
